#! /usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright © 2016 lizongzhe
#
# Distributed under terms of the MIT license.
from django.core.cache import cache
from proxy_manager.core import ProxyManager
import urlparse
from esr_parser import proxy_pool
import logging
import timeout_decorator
import requests

ORDER_LIST = ['general', 'sales', 'credit', 'pricing', 'popular']

logger = logging.getLogger(__name__)


@timeout_decorator.timeout(5, use_signals=True)
def requests_get(*args,**kwargs):
    resp = requests.get(*args, **kwargs)
    return resp

def request(url, *args, **kwargs):
    from esr_parser import shortcuts
    proxy = None
    cookies = shortcuts.get_cookies()
    count = 0
    t_c = 0
    e_c = 0
    u_p = []
    while True:
        try:
            if proxy:
                proxies = {}
                proxies['https'] = "{}:{}".format(proxy.ip, proxy.port)
                u_p.append(proxies['https'])
                auth = proxy.auth
                resp = requests_get(url, proxies=proxies, auth=auth, timeout=5, cookies=cookies, **kwargs)
            else:
                resp = requests_get(url, timeout=5, cookies=cookies, **kwargs)

            resp_url = resp.url
            assert 'alisec.taobao.com' not in resp_url, 'taobao block'
            assert 'sec.taobao.com' not in resp_url, 'taobao block'
            assert "window.location.href='https://sec.taobao.com" not in resp.content, 'taobao block'
            if proxy:
                proxy_pool.capture(proxy)
            msg = 'url: {} retry: {} error: {} timeout: {} proxys: {}'.format(url, count, e_c, t_c, u_p)
            print msg
            logger.debug(msg)
            return resp
        except timeout_decorator.TimeoutError:
            t_c += 1
            proxy = proxy_pool.get()
        except AssertionError as e:
            count += 1
            if count >= 2:
                msg = 'error url: {} retry: {} error: {} timeout: {} proxys: {}'.format(url, count, e_c, t_c, u_p)
                print msg
                logger.error(msg)
                return
            cookies = shortcuts.get_cookies(False)
            proxy = proxy_pool.get()
        except Exception as e:
            e_c += 1
            proxy = proxy_pool.get()



def update_proxies(focus=False):
    if cache.get('proxies', None) and not focus:
        return
    p_m = ProxyManager()
    cache.set('proxies', p_m.proxies, 600)


def attach_proxy(key):
    while True:
        proxy = cache.get('proxies').pop()
        if cache.get(proxy, None) == None:
            cache.set(proxy, key)
            return proxy


def get_item_id(url):
    urlinfo = urlparse.urlparse(url)
    params = urlparse.parse_qs(urlinfo.query)
    if 'world.taobao.com/item' in url:
        # https://world.taobao.com/item/528835992185.htm?fromSite=main
        return urlinfo.path.split('/')[-1].split('.')[0]
    elif 'item.taobao.com/item' in url:
        # https://item.taobao.com/world/item.htm?ft=t&toSite=main&id=528835992185
        return params['id'][0]
    elif 'world.tmall.com/' in url:
        # https://world.tmall.com//529101024223.htm?spm=a312a.7700714.0.0.U4keTG&sku_properties=10004:709990523;5919063:6536025
        return urlinfo.path.split('/')[-1].split('.')[0]
    elif 'detail.m.tmall.com/item' in url:
        # http://detail.m.tmall.com/item.htm?spm=0.0.0.0.QdzvZF&id=522157359219&sid=4992eb8e66f4909a1adaa1fdb8cc85d6&rn=849e410ccdaef4b28371f2c47718d6a6&abtest=7
        return unicode(params['id'][0])
    elif 'm.intl.taobao.com/detail' in url:
        # m.intl.taobao.com/detail/detail.html?spm=0.0.0.0.vEFW04&id=529091666938&sid=e6ab1fd1e09cb8fd2120b6b153c8b47e&rn=e905b22ea88963ef8994c7a50de1fa6e&abtest=28
        return params['id'][0]
    elif 'a.m.taobao.com' in url:
        # http://a.m.taobao.com/i41919276717.htm?spm=0.0.0.0.OZMEne&sid=951034ee11a131dc6ae40d69de5446c7&rn=841934052627e4ba4d9340130c5cf62a&abtest=29
        return urlinfo.path.split('/')[-1].split('.')[0][1:]
    elif 'detail.m.tmall.com/item.htm' in url:
        # http://detail.m.tmall.com/item.htm?id=522157359219&sid=44aa43779a35eae26349ffc410ce3f4b&rn=0ad704927ca383cb8cb799e95549a59c&abtest=20
        return params['id'][0]
    elif 'detail.tmall.com/item.htm':
        # https://detail.tmall.com/item.htm?id=522155891308&ad_id=&am_id=&cm_id=140105335569ed55e27b&pm_id=&abbucket=14
        return params['id'][0]
    raise Exception('url {} not support '.format(url))
